﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarShop
{
    public class Dealership<T> : IEnumerable
    {
        public event EventHandler<DealerShipEventArgs> RaiseChangeEvent;
        public EventArgs e = null;
        const int maxCapacity = 30;
        private T[] vehicles;
        private int count;

        public Dealership()
            : this(maxCapacity)
        {
        }

        public Dealership(int capacity)
        {
            vehicles = new T[capacity];
        }
        public int Count
        {
            get
            {
                return this.count;
            }
        }
        public void AddVehicle(T element)
        {
            if (count >= vehicles.Length)
            {
                throw new IndexOutOfRangeException("Sold one first!");
            }
            this.vehicles[count] = element;
            count++;

            OnDealerShipEventArgs(new DealerShipEventArgs("Added new car to our dealership. Check it out now!"));
        }
        public T RemoveVehicle(int id)
        {
            if (id < 0 || id >= this.count)
            {
                throw new ArgumentOutOfRangeException(
                      "Invalid cell index: " + id);
            }

            T car = this.vehicles[id];

            for (int i = id; i < this.count - 1; i++)
            {
                this.vehicles[i] = this.vehicles[i + 1];
            }
            this.vehicles[this.count - 1] = default(T);
            this.count--;

            OnDealerShipEventArgs(new DealerShipEventArgs("Sold another car. Hurry up, there's not much left."));

            return car;
        }

        public IEnumerator GetEnumerator()
        {
            return (vehicles as IEnumerable<T>).GetEnumerator();
        }

        protected virtual void OnDealerShipEventArgs(DealerShipEventArgs e)
        {

            EventHandler<DealerShipEventArgs> handler = RaiseChangeEvent;

            // Event will be null if there are no subscribers 
            if (handler != null)
            {
                // Format the string to send inside the CustomEventArgs parameter
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

                // Use the () operator to raise the event.
                handler(this, e);
            }
        }
        public T this[int id]
        {
            get
            {
                return vehicles[id];
            }

            set
            {
                this.vehicles[id] = value;
            }
        }

    }
}
